﻿using Model;
using Model.Modules;
using Proxy;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Utility;

namespace ViewModel
{
    class VM_PageHistoryAlerm : BaseViewModel
    {

        #region 变量
        public static surfacedetectEntities surfaceEntities;

        public DateTime Start { get { return start; } set { start = value; OnPropertyChanged(); } }
        private DateTime start;
        public DateTime End { get { return end; } set { end = value; OnPropertyChanged(); } }
        private DateTime end;


        public ObservableCollection<image> Imagelist { get { return imagelist; } set { imagelist = value; OnPropertyChanged(); } }
        private ObservableCollection<image> imagelist;

        public ObservableCollection<image_defect> Defectlist { get { return defectlist; } set { defectlist = value; OnPropertyChanged(); } }
        private ObservableCollection<image_defect> defectlist;

        public ObservableCollection<steeldefectinfo> SteelDefectlist { get { return steeldefectlist; } set { steeldefectlist = value; OnPropertyChanged(); } }
        private ObservableCollection<steeldefectinfo> steeldefectlist;

        public steeldefectinfo CurrentSteelDefect { get { return currentSteelDefect; } set { currentSteelDefect = value; OnPropertyChanged(); QueryImageInfo(); } }
        private steeldefectinfo currentSteelDefect;

        public ObservableCollection<Imagedefectinfo> ImageDefectlist { get { return imagedefectlist; } set { imagedefectlist = value; OnPropertyChanged(); } }
        private ObservableCollection<Imagedefectinfo> imagedefectlist;

        public ObservableCollection<Imagedefectinfo> CurrentList { get { return currentList; } set { currentList = value; OnPropertyChanged(); } }
        private ObservableCollection<Imagedefectinfo> currentList;
        public ObservableCollection<Imagedefectinfo> CurrentImageList { get { return currentImageList; } set { currentImageList = value; OnPropertyChanged(); } }
        private ObservableCollection<Imagedefectinfo> currentImageList;

        public int IgnoreCount { get { return ignoreCount; } set { ignoreCount = value; OnPropertyChanged(); } }
        private int ignoreCount;
        public int WarningCount { get { return warningCount; } set { warningCount = value; OnPropertyChanged(); } }
        private int warningCount;
        public int AlertCount { get { return alertCount; } set { alertCount = value; OnPropertyChanged(); } }
        private int alertCount;




        public ObservableCollection<batch> Batchlist { get { return batchlist; } set { batchlist = value; OnPropertyChanged(); } }
        private ObservableCollection<batch> batchlist;
        public batch CurrentBatch { get { return currentBatch; } set { currentBatch = value; OnPropertyChanged(); } }
        private batch currentBatch;
        public string Message { get { return message; } set { message = value; OnPropertyChanged(); } }
        private string message;

        public ObservableCollection<SteelDefectItemCount> SteelDefectSumSumList { get { return steelDefectSumSumList; } set { steelDefectSumSumList = value; OnPropertyChanged(); } }
        private ObservableCollection<SteelDefectItemCount> steelDefectSumSumList;
        

        public int CurrentImageIndex
        {
            get { return currentImageIndex; }
            set
            {
                currentImageIndex = value;
                OnPropertyChanged();
                //imagesFactory.UpdateImage(CurrentImageIndex);
            }
        }
        private int currentImageIndex;


        public Imagedefectinfo CurrentImg
        {
            get { return currentImg; }
            set
            {
                currentImg = value; OnPropertyChanged();
            }
        }
        private Imagedefectinfo currentImg;


        public image_defect CurrentDefect
        {
            get { return currentDefect; }
            set
            {
                currentDefect = value; OnPropertyChanged();
            }
        }
        private image_defect currentDefect;


        ESDataHelper eshelper;
        ImagesVirtualFactory imagesFactory;
        TestEntitity testEntitity;
        public int PageNumber { set; get; }
        private bool HasSearchAll { set; get; }
        public List<DateTime> LastTimeList { set; get; }

        #endregion


        public VM_PageHistoryAlerm()
        {

            InitData();
            SearchByDateRange();
            
        }

        private void InitData()
        {
            
            var startdate = DateTime.Now.AddDays(-1);
            Start = new DateTime(startdate.Year, startdate.Month, startdate.Day);
            End = DateTime.Now;
            PageNumber = 1;
            LastTimeList = new List<DateTime>();

            eshelper = new ESDataHelper();
            CurrentList = new ObservableCollection<Imagedefectinfo>();
            surfaceEntities = new surfacedetectEntities();
            if (StaticData.DataBase== DataFrom.ES)
                try
                {

                    Batchlist = new ObservableCollection<batch>(surfaceEntities.batch.OrderByDescending(o=>o.insert_time).Take(100).ToList());
                }
                catch(Exception e)
                {
                    Logger.Error(e);
                }

            else
                Batchlist = new ObservableCollection<batch>(surfaceEntities.batch.Take(50).ToList());
            CurrentBatch = Batchlist[0];

            imagesFactory = new ImagesVirtualFactory( PageName.PageHistory, InsertAt.Top,true,0,CurrentList, null);
            imagesFactory.Run();

            SteelDefectlist = new ObservableCollection<steeldefectinfo>();
            ImageDefectlist = new ObservableCollection<Imagedefectinfo>();
            Logger.Info("SuccessInitHistoryData");
            
        }

        private void SearchByDateRange() {
            try
            {
                //SteelDefectSumSumList = eshelper.GetSteelDefectItemCountList(Start, End);
                PageNumber = 1;
                LastTimeList.Clear();
                LastTimeList.Add(End);
                QuerySteelDefectList();
        }
            catch (Exception ee)
            {
                Logger.Error(ee);
            }
        }

        private async void QueryImageInfo()
        {
            
            var _iamgelist = new ObservableCollection<image>();
            var _defectlist = new ObservableCollection<image_defect>();
            //Diff 仅永钢使用image_defect_ids_text，其他都用image_defect_ids
            var ids =CurrentSteelDefect.Steel_defect.image_defect_ids_text.Split(',');
            Logger.Info($"{CurrentSteelDefect.Steel_defect.image_defect_ids_text}");
            if (StaticData.DataBase == DataFrom.ES)
            {
                _defectlist =await eshelper.GetDefectsByIDs(ids);
                _iamgelist = await eshelper.GetImagesByIDs(_defectlist.Select(t => t.image_id).ToArray());
                Logger.Info($"{_defectlist.Count}-----{_iamgelist.Count}");
            }
            else if(StaticData.DataBase == DataFrom.Test)
            {
                testEntitity = new TestEntitity(CurrentBatch.main_id);

                _iamgelist = new ObservableCollection<image>(testEntitity.Imagelist);

                _defectlist = new ObservableCollection<image_defect>(testEntitity.Defectlist);
            }

            //Logger.Info(_defectlist.Count.ToString());
            //Logger.Info(_iamgelist.Count.ToString());
            var imageinfolist = new List<Imagedefectinfo>();
            foreach (var defect in _defectlist)
            {
                Imagedefectinfo info = new Imagedefectinfo();
                info.Image_DefectList[0] = defect;
                var tempimagelist = _iamgelist.Where(t => t.id == defect.image_id);
                if (tempimagelist.Count() != 1)
                {
                    continue;
                }
                else
                {
                    var image = _iamgelist.Where(t => t.id == defect.image_id).First();

                    image.image_url = image.image_url.Replace('/', '\\');
                    info.Image = image;
                    imageinfolist.Add(info);
                }

            }
            imageinfolist = new List<Imagedefectinfo>(imageinfolist.OrderBy(t => t.Image.flow_id)) ;
            if (imageinfolist.Count > 0)
            {
                ImageDefectlist = new ObservableCollection<Imagedefectinfo>(imageinfolist);
                imageinfolist.First().IsFirst = true;
                //imagesFactory.AddImageInfos(imageinfolist);
            }


        }

        private async void QuerySteelDefectList()
        {
            try
            {


            HasSearchAll = false;
            var _steeldefectlist = new ObservableCollection<steel_defect>();
            var _iamgelist = new ObservableCollection<image>();
            var _defectlist = new ObservableCollection<image_defect>();


            if (StaticData.DataBase == DataFrom.ES)
            {
                _steeldefectlist = await eshelper.GetSteelDefectsDuringDate(Start, LastTimeList[PageNumber-1]);
                if (_steeldefectlist.Count < 8000)
                    HasSearchAll = true;
                else
                    LastTimeList.Add((DateTime)_steeldefectlist.Last().insert_time);

                Logger.Info($"查询到了{_steeldefectlist.Count}个steel_defect");

            }
            else if (StaticData.DataBase == DataFrom.Test)
                _steeldefectlist = new ObservableCollection<steel_defect>(testEntitity.SteelDefectslist);


            var steeldefectinfolist = new List<steeldefectinfo>();
            foreach (var steel_defect in _steeldefectlist)
            {
                steeldefectinfo steeldefectinfo = new steeldefectinfo();
                steeldefectinfo.Steel_defect = steel_defect;
                steeldefectinfolist.Add(steeldefectinfo);
            }
            SteelDefectlist = new ObservableCollection<steeldefectinfo>(steeldefectinfolist);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }




        private void CalcAlertCount(int total)
        {
            var r = new Random();
            var r1 = r.NextDouble();
            var r2 = r.NextDouble();
            var r3 = r.NextDouble();
            var sum = r1 + r2 + r3;
            IgnoreCount = (int)(total * r1 / sum);
            WarningCount = (int)(total * r2 / sum);
            AlertCount = (int)(total * r3 / sum);

        }

        public BaseCommand SearchCommand { get => new BaseCommand(SearchCommand_Executed); }
        public void SearchCommand_Executed(object obj)
        {

            SearchByDateRange();
        }

        public BaseCommand ConfigCommand { get => new BaseCommand(ConfigCommand_Executed); }
        public void ConfigCommand_Executed(object obj)
        {
            new VM_WindowGradeConfig().ShowDialog();
        }

        public BaseCommand PreviousCMD { get => new BaseCommand(PreviousCMD_Executed); }
        public void PreviousCMD_Executed(object obj)
        {
            if (PageNumber == 1)
                return;
            PageNumber--;
            QuerySteelDefectList();
        }
        public BaseCommand NextCMD { get => new BaseCommand(NextCMD_Executed); }
        public void NextCMD_Executed(object obj)
        {
            if (HasSearchAll)
                return;
            PageNumber++;
            QuerySteelDefectList();
        }

        }

    public class SteelDefectItemCount
    {
        public DateTime Date { get; set; }
        public int Warning { get; set; }
        public int Alert { get; set; }
        public int Ignore { get; set; }
        
    }
}
